package com.snail.utils;

import cn.hutool.core.util.StrUtil;
import com.snail.model.pojo.SysUser;
import com.snail.exception.BusinessException;
import com.snail.exception.ErrorCode;
import com.snail.service.SysUserService;
import org.springframework.stereotype.Component;

/**
 * @Author 蔡徐坤
 * @Date 2025/7/15 10:21
 * @Description: 封装用户的验证和登录逻辑
 */

@Component
public class UserValidator {

    /**
     * 校验用户参数（注册、登录）  StrUtil.isBlank() 用于判断字符串是否为空
     */
    public void validateUserParams(SysUser sysUser) {
        if (sysUser == null || StrUtil.isBlank(sysUser.getUsername()) || StrUtil.isBlank(sysUser.getPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
    }

    /**
     * 检查用户名是否已存在（注册使用）
     * 检查用户名是否已存在  User::getUsername Mybatis-Plus自动解析为数据库的username的字段
     * lambdaQuery() 用于构建查询条件，eq()相当于equal()，one() 用于返回唯一的结果
     */
    public void checkUsernameIsExist(String username, SysUserService sysUserService) {
        SysUser existSysUser = sysUserService.lambdaQuery()
                .eq(SysUser::getUsername, username)
                .one();
        if (existSysUser != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
    }

    /**
     * 根据用户名获取用户（登录使用）
     */
    public SysUser getUserByUsername(String username, SysUserService sysUserService) {
        SysUser sysUser = sysUserService.lambdaQuery()
                .eq(SysUser::getUsername, username)
                .one();
        if (sysUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        return sysUser;
    }

}
